package cn.jtool.dig.server.comm.tunnel.protocol;

import cn.jtool.dig.common.model.Commands;
import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketHeader;
import cn.jtool.dig.common.model.Session;
import cn.jtool.dig.common.netty.ProtocolProcess;
import cn.jtool.dig.common.netty.SessionManager;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 向设备端发送数据
 */
@Slf4j
@Component
public class P_50_DataTransparent implements ProtocolProcess {

    @Override
    public int protocolId() {
        return Commands.DATA_TRANSPARENT.getCode();
    }

    @Override
    public Packet process(ChannelHandlerContext ctx, Packet packet) {
        PacketHeader header = packet.getHeader();
        Session session = SessionManager.getSession(header.getChannelId());
        if(Objects.nonNull(session) && Objects.nonNull(session.getChannelHandlerContext())){
            if(session.getChannelHandlerContext().channel().isActive()){
                session.getChannelHandlerContext().channel().writeAndFlush(packet);
            }
        }
        return null;
    }
}
